Introduction to R shiny package

Hakan Turgay & Bertan Taylan

Chapter 1

Motivation, Basic R-Shiny Package and Example

Motivation

  • Scientists mostly use R to process their analyzes

  • Presenting/Sharing their findings are usually done in static format

  • Problem : They cannot present additional questions directly

  • Simple idea: Immigrating ratios from a specific region of Turkey due to years and also forecasts about these ratios (e.g. Journalist)

What is Shiny package?

  • Shiny is an R package that makes it easy to build interactive web applications (apps) straight from R. This lesson will get you started building Shiny apps right away.
  • Build useful web applications with only a few lines of code—no JavaScript required.
  • Shiny applications are automatically “live” in the same way that spreadsheets are live. Outputs change instantly as users modify inputs, without requiring a reload of the browser.
  • Shiny user interfaces can be built entirely using R, or can be written directly in HTML, CSS, and JavaScript for more flexibility.
  • Pre-built output widgets for displaying plots, tables, and printed output of R objects.

Basically


R Shiny = R + interactivity + web made easy

kmeans

Install Shiny Package

If you still haven’t installed the Shiny package, open an R session, connect to the internet, and run

install.packages("shiny")

First App in Shiny

library(shiny)
runExample("01_hello")

Code Output

firstapp

More Example

runExample("01_hello")      # a histogram
runExample("02_text")       # tables and data frames
runExample("03_reactivity") # a reactive expression
runExample("04_mpg")        # global variables
runExample("05_sliders")    # slider bars
runExample("06_tabsets")    # tabbed panels
runExample("07_widgets")    # help text and submit buttons
runExample("08_html")       # Shiny app built from HTML
runExample("09_upload")     # file upload wizard
runExample("10_download")   # file download wizard
runExample("11_timer")      # an automated timer

Chapter 2

Structure of a Shiny App

Main Structure

  • ui: Nested R functions that assemble an HTML user interface for the app

  • server : A function with instructions on how to build and rebuild the R objects displayed in the UI

  • shinyApp : Combines ui and server into a functioning app

  • Save the template as app.R

  • a call to the shinyApp function

    library(shiny)
    
    ui <- fluidPage(
     
    )
    
    server <- function(input, output, session) {
      
    }
    
    shinyApp(ui, server)

Alternative Approach

kmeans

Say Hello with Shiny

library(shiny)
ui <- fluidPage(
    "Hello Shiny Package"
    )

server <- function(input, output) {
    
}

shinyApp(ui = ui, server = server)

Code Output

working code:

helloshiny

Chapter 3

Inputs and Outputs

Overview

Build your app around inputs and outputs

kmeans

Input Syntax

kmeans

Input

sliderInput(inputId = "num",
  label = "Choose a number",
  value = 25, min = 1, max = 100)
library(shiny)
ui <- fluidPage(
    sliderInput(inputId = "num",
                label = "Choose a number",
                value = 25, min = 1, max = 100)
    )

server <- function(input, output) {
    
}

shinyApp(ui = ui, server = server)

Code Output

input

Entegration Input and Output

Use 3 rules to write the server function

server <- function(input, output) {




}

1 - Save objects to display to output$


server <- function(input, output) {  
  output$hist <- # code
}
First Rule

kmeans

2 - Build objects to display with render*()

[ING] UI tarafinda bulunan ‘hist’ (histogram) objesi server tarafindaki ‘RenderPlot’ methodu ile uretilecek . Not: hist ve RenderPlot vurgulanacak ..


server <- function(input, output) {  
  output$hist <- renderPlot({

   #code

  }) 
}

Render Method

First Rule


server <- function(input, output) {
  output$hist <- renderPlot({

    title <- "100 random normal values"           

    hist(rnorm(100), main = title) 

  }) 
}

3 - Access input values with input$

server <- function(input, output) {  
  
  output$hist <- renderPlot({    
  hist(rnorm(input$num))  
  
  }) 

}

First Rule

…and more “Render Method” example

First Rule

Result (Reactivity)

Reactivity automatically occurs whenever you use an input value to render an output object

library(shiny)
ui <- fluidPage(
    sliderInput(inputId = "num",
                label = "Choose a number",
                value = 25, min = 1, max = 100),
    plotOutput("hist")
    )

server <- function(input, output) {
    output$hist <- renderPlot({
        hist(rnorm(input$num))
    })
}

shinyApp(ui = ui, server = server)

Code Output

working code:

res

Chapter 4

Using Checkbox in Shiny

Reviewing an Example

library(shiny)
runExample("02_text")
kmeans

Starting to Code Analysis

kmeans

Change code

library(shiny)

ui <- fluidPage(
  titlePanel("Shiny Text"),
  sidebarLayout(
    
    sidebarPanel(
      
      checkboxGroupInput("dataset", "Choose a dataset:",
                         c("rock", "pressure", "cars"),
                         selected = "rock"),
                         
      numericInput(inputId = "obs",
                   label = "Number of observations to view:",
                   value = 10)
    ),
    
    mainPanel(
      verbatimTextOutput("summary"),
      tableOutput("view")
    )
  )
)

Result

working code:

check

Chapter 5

Improving the Design

Design Part

  • Assemble UI with HTML/CSS/… widgets

  • Adjustment of the layout scheme

Chapter 6

Implementations in Shiny: JavaScript, HTML and CSS

Using HTML, CSS and Javascript in R Code


In R, HTML elements can be defined by tags keyword.
ui <fluidPage (
tags$h1(”R Shiny Introduction”) ,
tags$hr () ,
tags$br () ,
tags$p(strong(”Istanbul Technical University”)),
tags$p(em(”Mathematical Engineering”)),
tags$a(href=”https://www.itu.edu.tr”, ”Website”))
server <function(input , output){} > 
shinyApp(ui = ui , server = server)

tags

…and more Html Tag

html tag

External file import (html, css , js ext)

Method of importing depends on type of the file;

To include a CSS file


use includeCSS() or
1. Place the file in the www subdirectory
2. Link to it with:

tags$head(tags$link(rel = "stylesheet",
type = "text/css", href = "<file name>"))

To include JavaScript


use includeScript() or
1. Place the file in the www subdirectory
2. Link to it with:

tags$head(tags$script(src = "<file name>"))

To include HTML file

includeHTML("include.html")

Layout structure of the UI

Combine multiple elements into a ”single element” that has its own properties with a panel function

  ui <-
    fluidPage (
    wellPanel(
    numericInput(inputId = 'n', 'Sample size', value = 25),
    submitButton () ) , plotOutput(outputId = 'hist'))
  server <- function(input , output ){
  } > 
  shinyApp(ui = ui , server = server)

working code:

submit

Chapter 7

Introduction to HTMLWidgets Package

Overview

  • This package builds a framework for creating R bindings to JavaScript libraries. HTMLWidgets can be
    • Used at the R console for data analysis
    • Embedded within R Markdown documents
    • Incorporated into Shiny web applications

Creating a Widget

  • Three elements forms the widget:

    • Dependencies : JavaScript and CSS assets will be used by the widget
    • R binding : This is the function where R stuff happens
    • JavaScript binding : JavaScript code that connects everything and passes the data and the choices collected from the R binding to the JavaScript library which is (are) using in widget

Some most-used HTMLWidget Examples

kmeans


leaflet

kmeans


dygraph

Creating a widget step-by-step

Requirements

  • We need to create a new R package that relies on the htmlwidgets package.
install.packages("htmlwidgets")

Scaffolding

To create a new widget you can call the scaffoldWidget function to generate the basic structure for your widget. This function will:

  • Create the .R, .js, and .yaml files required for your widget
  • Tip: If provided, take a Bower package (which is a package manager for web) name and automatically download the JavaScript library (and its dependencies) and add the required entries to the .yaml file. This method is highly preferrable because it guarantees that you get started with the right file structure.

MyWidget

We want to create a widget named ‘mywidget’ in a new package of the same name:

devtools::create("mywidget")               # create package using devtools
setwd("mywidget")                          # navigate to package dir
htmlwidgets::scaffoldWidget("mywidget")    # create widget scaffolding
devtools::install()                        # install the package so we can try it
  • This creates a simple widget that takes a single text argument and displays that text within the widgets HTML element. You can try it like this:
library(mywidget)
mywidget("hello, world")
  • This is the most minimal widget possible and doesn’t yet include a JavaScript library.

Chapter 8

Case Studies: Predicted Deaths from Lung Disease

Using DyGraph Package in Shiny

Ui part of the code:

ui <- fluidPage(
  
  titlePanel("Predicted Deaths from Lung Disease (UK)"),
  
  sidebarLayout(
    sidebarPanel(
      numericInput("months", label = "Months to Predict", 
                   value = 72, min = 12, max = 144, step = 12),
      selectInput("interval", label = "Prediction Interval",
                  choices = c("0.80", "0.90", "0.95", "0.99"),
                  selected = "0.95"),
      checkboxInput("showgrid", label = "Show Grid", value = TRUE),
      hr(),
      div(strong("From: "), textOutput("from", inline = TRUE)),
      div(strong("To: "), textOutput("to", inline = TRUE)),
      div(strong("Date clicked: "), textOutput("clicked", inline = TRUE)),
      div(strong("Nearest point clicked: "), textOutput("point", inline = TRUE)),
      br(),
      helpText("Click and drag to zoom in (double click to zoom back out).")
    ),
    mainPanel(
      dygraphOutput("dygraph")
    )

Server part of the code

server <- function(input, output) {
  
  predicted <- reactive({
    hw <- HoltWinters(ldeaths)
    predict(hw, n.ahead = input$months, 
            prediction.interval = TRUE,
            level = as.numeric(input$interval))
  })
  output$dygraph <- renderDygraph({
    dygraph(predicted(), main = "Predicted Deaths/Month") %>%
      dySeries(c("lwr", "fit", "upr"), label = "Deaths") %>%
      dyOptions(drawGrid = input$showgrid)
  })
  output$from <- renderText({
    strftime(req(input$dygraph_date_window[[1]]), "%d %b %Y")      
  })
  output$to <- renderText({
    strftime(req(input$dygraph_date_window[[2]]), "%d %b %Y")
  })
  output$clicked <- renderText({
    strftime(req(input$dygraph_click$x), "%d %b %Y")
  })
  output$point <- renderText({
    paste0('X = ', strftime(req(input$dygraph_click$x_closest_point), "%d %b %Y"), 
           '; Y = ', req(input$dygraph_click$y_closest_point))
  })

Result

check

Chapter 9

Case Studies: Migration

Retrieving Data

Using Leaflet

  • For creating a map we used Leaflet library.
  • Leaflet is a open source JavaScript library for creating interactive maps.
  • It can be implemented and used in Shiny easily.
  • Leaflet gives the opportunity of adding informational popups to particular part of maps.
  • leaflet

Result

result